package com.snc.util;

import com.snc.exception.ParameterException;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 动态码的工具类，短信验证码/随机码之类的
 * Created by Administrator on 2016/5/19 0019.
 */
public class DynamicCodeUtils {
    //短信验证码集成，KEY = 手机号码，VALUE = 验证码和生成时间
    private static Map<String,SMSCode> SMS_CODES = new HashMap<String, SMSCode>();

    /**
     * 随机生成4位数的动态码
     * @return 动态码
     */
    public static String generateSMSCode(){
        int code = (int)(Math.random()*9000+1000);
        return code + "";
    }

    /**
     * 发送短信验证码（该方案无法在集群时使用，废除）
     */
    @Deprecated
    public static void sendSMSCode(String phone){
        if(StringUtils.isEmpty(phone)){
            throw new ParameterException("请填写手机号码");
        }

        String code = "8888";
        Date now = new Date();
        SMSCode sms = new SMSCode(code,now);

        //放入缓存中
        SMS_CODES.put(phone,sms);

    }


    /**
     * 验证短信验证码
     * @param phone 手机号码
     * @param code 验证码
     * @return true，验证通过，false，验证不通过
     */
    public static boolean validSMSCode(String phone,String code){
        if(StringUtils.isEmpty(phone)){
            throw new ParameterException("请填写手机号码");
        }

        if(StringUtils.isEmpty(code)){
            throw new ParameterException("请填写验证码");
        }

        SMSCode smsCode = SMS_CODES.get(phone);
        Date now = new Date();
        if(now.getTime() - smsCode.getGmtTime().getTime() > 1000 * 60 * 30){
            throw new ParameterException("验证码已失效，请重新发送");
        }

        return smsCode.getCode().equals(code);
    }

}
class SMSCode{
    private String code;//短信验证码
    private Date gmtTime;//生成时间

    public SMSCode(String code, Date gmtTime) {
        this.code = code;
        this.gmtTime = gmtTime;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Date getGmtTime() {
        return gmtTime;
    }

    public void setGmtTime(Date gmtTime) {
        this.gmtTime = gmtTime;
    }
}
